import 'dart:convert';

import 'package:hambuk/config/apiConfig.dart';
import 'package:hambuk/util/ApiUri.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart';

import '../model/FilmModel.dart';

class HttpService {
  /*{
  page:
  页码

  category:
  动作/剧情/戏剧/综艺/爱情/科幻/恐怖/动画/事故:11~19

  contentType:
  电影/电视剧/综艺:0/1/2

  sortType:
  最新/热门/推荐:1/2/3

  year:
  年份
  -}*/
  /*获取全部视频列表*/
  Future<List<FilmModel> ? > getAllFilm(
      int page, int category, int contentType, int sortType, int year) async {
    /*String filmApi = "/h5/films?page=$page&content_type=$contentType&sortType=$sortType&category=$category&year=$year";*/
    /*参数拼接*/
    Map<String, dynamic> params = {
      'page': page,
      'category': category,
      'content_type': contentType,
      'sort_type': sortType,
      'year': year
    };
    String filmApi =
        "/h5/films?${params.entries.where((entry) => entry.value != -1).map((entry) => "${entry.key}=${entry.value}").join("&")}";
    Response response = await get(ApiUri().apiUri(filmApi));
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['status'] == 200) {
        final List result = jsonDecode(response.body)['data']['data'];
        if (result.isEmpty) {
          Toasts('تۈگەپ قالدى');
          return null;
        }
        return result.map((e) => FilmModel.fromJson(e)).toList();
      } else {
        return null;
      }
    } else {
      /* 失败 */
      /*throw Exception('Failed to fetch video URL');*/
      Toasts('كاشىلا چىقتى');
    }
  }

  /*搜索*/
  Future<List<FilmModel>?> searchFilm(String name) async {
    String url = "/h5/search";
    Map<String, Object> params = {'name': name};
    Response response = await post(ApiUri().apiUri(url), body: params);
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['status'] == 200) {
        final List result = jsonDecode(response.body)['data']['movies']['data'];
        if (result.isEmpty) {
          Toasts('تاپالمىدىم');
          return null;
        }
        return result.map((e) => FilmModel.fromJson(e)).toList();
      } else {
        return null;
      }
    } else {
      /* 失败 */
      /*throw Exception('Failed to fetch video URL');*/
      Toasts('كاشىلا چىقتى');
    }
  }

  /*电影解析*/
  Future<String?> getVideoUrl(int id) async {
    String apiUrl = "/h5/detail?id=$id&type=0";
    final Map<String, String> headers = {
      'Open-Id': ApiConfig().getOpenID(),
      'Token': ApiConfig().getToken()
    };
    /* 发送 POST 请求 */
    Response response = await get(ApiUri().apiUri(apiUrl), headers: headers);
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['status'] == 200) {
        final responseData = json.decode(response.body);
        /* 从 JSON 数据中获取视频的 URL */
        if (responseData['data']['url'] == null ||
            responseData['data']['url'].isEmpty) {
          Toasts('كىنو نورمال ئەمەس');
          return null;
        }
        return responseData['data']['url'];
      } else {
        Toasts('كىنو نورمال ئەمەس');
        return null;
      }
    } else {
      /*throw Exception('Failed to fetch video URL');*/
      Toasts('كاشىلا چىقتى');
    }
  }

  /*电视剧*/
  Future<String?> getVideoUrlMore(int id) async {
    String apiUrl = "/h5/episode-url/$id/1";
    /* 发送 POST 请求 */
    Response response = await get(ApiUri().apiUri(apiUrl));
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['status'] == 200) {
        final responseData = json.decode(response.body);
        /* 从 JSON 数据中获取视频的 URL */
        if (responseData['data']['url'] == null ||
            responseData['data']['url'].isEmpty) {
          Toasts('كىنو نورمال ئەمەس');
          return null;
        }
        return responseData['data']['url'];
      } else {
        Toasts('كىنو نورمال ئەمەس');
        return null;
      }
    } else {
      /*throw Exception('Failed to fetch video URL');*/
      Toasts('كاشىلا چىقتى');
    }
  }

  /*返回详细数据*/
  Future<Response?> getVideoDetail(int id) async {
    String apiUrl = "/h5/detail?id=$id&type=1";
    final Map<String, String> headers = {
      'Open-Id': 'ozXNM5irkC6I4w6YvjTWiiko2Yl4',
      'Token': '1uu0ULSIjRptG4ipXUz1c6hV9LS2EwEg'
    };
    /* 发送 POST 请求 */
    Response response = await get(ApiUri().apiUri(apiUrl), headers: headers);
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['status'] == 200) {
        final responseData = json.decode(response.body);
        /* 从 JSON 数据中获取视频的 URL */
        if (responseData != null) {
          return response;
        }
        return null;
      } else {
        /*throw Exception('Failed to fetch video URL');*/
        Toasts('كاشىلا چىقتى');
        return null;
      }
    } else {
      Toasts('كاشىلا چىقتى');
      return null;
    }
  }

  Future<void> Toasts(String msg) async {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
